/** http库，暴露以下接口：
 *  - request(obj): obj必须包含 url
 *  - get(url, data, config): url必填，config同request里的obj结构 
 *  - post(url, data, config): url必填，config同request里的obj结构
 */

const common = require('./common');
const app = getApp();

let handleError = res => {
    if (res.statusCode === 200) {
        //
    } else {
        common.toast(res.data);
    }
};

const http = {
    request: params => {
        return new Promise((resolve, reject) => {
            wx.request({
                url: `https://spapi.searchencrypt.com/${params.url}`,
                // url: `https://cse.google.com/${params.url}`,
                data: params.data,
                method: params.method || 'GET',
                ...params.config,
                success: (res) => {
                    console.log('response', res);
                    if (res.statusCode === 200) {
                        resolve(res);
                    } else {
                        handleError(res);
                        reject(res);
                    }
                },
                fail: res => {
                    handleError(res);
                    reject(res);
                }
            })
        })
    },
    getConfig: (method, url, data, config = {}) => {
        let params = {
            url: url,
            method: method,
            config: {}
        };
        data && (params.data = data);
        config && Object.assign(params, config);
        return params;
    },
    get: (url, data, config) => {
        let params = http.getConfig('get', url, data, config);
        return http.request(params);
    },
    post: (url, data, config) => {
        let params = http.getConfig('post', url, data, config);
        return http.request(params);
    },
    put: (url, data, config) => {
        let params = http.getConfig('put', url, data, config);
        return http.request(params);
    },
    delete: (url, data, config) => {
        let params = http.getConfig('delete', url, data, config);
        return http.request(params);
    }
}

export default http;